﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using System.IO;

public partial class Main_Personal_Tasks : System.Web.UI.Page
{


    /*page defaults*/
    OfficeOnlineUser currentUser;

    private void AuthenticateUser()
    {
        try
        {
            currentUser = (OfficeOnlineUser)Session["CurrentUser"];
        }
        catch (Exception ex)
        {
            //Response.Redirect("../login.aspx?urlReferrer=" + Request.Url);
        }

        if (currentUser == null)
        {
            //Response.Redirect("../login.aspx?urlReferrer=" + Request.Url);
        }
    }
    /*end page defaults*/

    protected void Page_Load(object sender, EventArgs e)
    {
        
        AuthenticateUser();
        if (Request.QueryString["addtask"] == "1")
        {
            int result = AddTask();
            switch (result)
            {
                case 1:
                    form1.InnerHtml = "<response>" + "Success" + "</response>";
                    break;
                default:
                    form1.InnerHtml = "<response>" + "There was a problem trying to add the task, please try again or contact your administrator" + "</response>";
                    break;
            }
        }
        else if (Request.QueryString["edittask"] == "1")
        {
            int result = UpdateTask();
            switch (result)
            {
                case 1:
                    form1.InnerHtml = "<response>" + "Success" + "</response>";
                    break;
                default:
                    form1.InnerHtml = "<response>" + "There was a problem trying to update the task, please try again or contact your administrator" + "</response>";
                    break;
            }
        }
        else if (Request.QueryString["deletelink"] == "1")
        {
            int result = DeleteLink();
            switch (result)
            {
                case 1:
                    form1.InnerHtml = "<response>" + "Success" + "</response>";
                    break;
                default:
                    form1.InnerHtml = "<response>" + "There was a problem trying to delete the task, please try again or contact your administrator" + "</response>";
                    break;
            }
        }
        else
        {
            //page load events if your really loading the page
            this.txtTaskDueDate.Attributes.Add("onfocus", "showCalendarControl(this);");

            LoadTaskConfig();
            LoadTasks();
        }
    }

    private void LoadTaskConfig()
    {

        for (int i = 0; i < Config.TaskStatus.Length; i++)
        {
            ddTaskStatus.Items.Add(Config.TaskStatus[i]);
        }

    }

    private void LoadTasks()
    {
        string command = "sp_tb_task_GetUserTasks @userName='" + currentUser.UserName + "'";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        sqlCon.Open();
        SqlDataAdapter sda = new SqlDataAdapter(command, sqlCon);

        DataSet dsLinks = new DataSet();

        sda.Fill(dsLinks);

        sqlCon.Close();

        dgTasks.DataSource = dsLinks;

        dgTasks.DataBind();
    }

    protected void dgTasks_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        switch (e.Item.ItemType)
        {
            case ListItemType.Item:
            case ListItemType.AlternatingItem:
                e.Item.Attributes.Add("onclick", "selectTaskTableElement('" + e.Item.ClientID + "');");
                e.Item.Attributes.Add("taskNo", DataBinder.Eval(e.Item.DataItem, "taskNo").ToString());
                e.Item.Cells[3].Style.Add("cursor", "pointer");
                try{
                    e.Item.Cells[2].Text = Convert.ToDateTime(e.Item.Cells[2].Text).ToString(Config.DateTimeFormat);
                }catch(Exception ex)
                {
                    e.Item.Cells[2].Text= "";
                }
                break;
        }
    }

    private int AddTask()
    {

        string taskDescription = Request.QueryString["taskDescription"];
        string taskDueDate = Request.QueryString["taskDueDate"];
        string taskDetails = Request.QueryString["taskDetails"];
        string taskSessionId = Request.QueryString["taskSessionId"];

        string command = "sp_tb_task_InsertTask";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        SqlCommand sqlCmd = new SqlCommand(command, sqlCon);
        sqlCon.Open();
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;


        sqlCmd.Parameters.Add("@taskAssignedByUser", SqlDbType.VarChar, 50);
        sqlCmd.Parameters.Add("@taskDescription", SqlDbType.VarChar, 255);
        sqlCmd.Parameters.Add("@taskDetails", SqlDbType.VarChar, Int32.MaxValue);
        sqlCmd.Parameters.Add("@taskDueDate", SqlDbType.SmallDateTime, 50);
        sqlCmd.Parameters.Add("@result", SqlDbType.TinyInt, 8);
        sqlCmd.Parameters["@result"].Direction = ParameterDirection.Output;

        sqlCmd.Parameters["@taskAssignedByUser"].Value = currentUser.UserName;
        sqlCmd.Parameters["@taskDescription"].Value = taskDescription;
        sqlCmd.Parameters["@taskDetails"].Value = taskDetails;
        sqlCmd.Parameters["@taskDueDate"].Value = Convert.ToDateTime(taskDueDate);

        sqlCmd.ExecuteNonQuery();

        int result = 0;

        try
        {
            result = Convert.ToInt16(sqlCmd.Parameters["@result"].Value);
            CopyTempToUserFolder(taskSessionId);
        }
        catch (Exception ex)
        {
            result = 0;
        }

        sqlCon.Close();

        return result;  

        
    }

    private void CopyTempToUserFolder(string oprSessionId)
    {
        if (Session[oprSessionId] != null)
        {
            ArrayList taskUploadSession = (ArrayList)Session[oprSessionId];
            for (int i = 0; i < taskUploadSession.Count; i++)
            {
                string userPath = taskUploadSession[i].ToString(); 
                userPath = userPath.Replace(Config.TempUploadDirectory, Config.FileDirectory);
                string directoryName = Path.GetDirectoryName(userPath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                File.Copy(taskUploadSession[i].ToString(), userPath);
            }
        }
    }

    private int UpdateTask()
    {
        string taskNo = Request.QueryString["taskNo"];
        string taskDescription = Request.QueryString["taskDescription"];
        string taskDueDate = Request.QueryString["taskDueDate"];
        string taskDetails = Request.QueryString["taskDetails"];
        string taskSessionId = Request.QueryString["taskSessionId"];

        string command = "sp_tb_task_UpdateTask";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        SqlCommand sqlCmd = new SqlCommand(command, sqlCon);
        sqlCon.Open();
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;

        sqlCmd.Parameters.Add("@taskNo", SqlDbType.Int, 32);
        sqlCmd.Parameters.Add("@taskAssignedByUser", SqlDbType.VarChar, 50);
        sqlCmd.Parameters.Add("@taskDescription", SqlDbType.VarChar, 255);
        sqlCmd.Parameters.Add("@taskDetails", SqlDbType.VarChar, Int32.MaxValue);
        sqlCmd.Parameters.Add("@taskDueDate", SqlDbType.SmallDateTime, 50);
        sqlCmd.Parameters.Add("@result", SqlDbType.TinyInt, 8);
        sqlCmd.Parameters["@result"].Direction = ParameterDirection.Output;

        sqlCmd.Parameters["@taskNo"].Value = taskNo;
        sqlCmd.Parameters["@taskAssignedByUser"].Value = currentUser.UserName;
        sqlCmd.Parameters["@taskDescription"].Value = taskDescription;
        sqlCmd.Parameters["@taskDetails"].Value = taskDetails;
        sqlCmd.Parameters["@taskDueDate"].Value = Convert.ToDateTime(taskDueDate);

        sqlCmd.ExecuteNonQuery();

        int result = 0;

        try
        {
            result = Convert.ToInt16(sqlCmd.Parameters["@result"].Value);
            CopyTempToUserFolder(taskSessionId);
        }
        catch (Exception ex)
        {
            result = 0;
        }

        sqlCon.Close();

        return result;  
    }

    private int DeleteLink()
    {
        string linkNo = Request.QueryString["linkNo"];
        

        string command = "sp_tb_links_DeleteLink";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        SqlCommand sqlCmd = new SqlCommand(command, sqlCon);
        sqlCon.Open();
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;

        sqlCmd.Parameters.Add("@linkNo", SqlDbType.Int, 16);
        sqlCmd.Parameters.Add("@userName", SqlDbType.VarChar, 50);
        sqlCmd.Parameters.Add("@result", SqlDbType.Int, 16);
        sqlCmd.Parameters["@result"].Direction = ParameterDirection.Output;

        sqlCmd.Parameters["@linkNo"].Value = linkNo;
        sqlCmd.Parameters["@userName"].Value = currentUser.UserName;
        
        sqlCmd.ExecuteNonQuery();

        int result = 0;

        try
        {
            result = Convert.ToInt16(sqlCmd.Parameters["@result"].Value);
        }
        catch (Exception ex)
        {
            result = 0;
        }

        sqlCon.Close();

        return result;  
    }
}
